//
//  BYNetworkMananger.swift
//  Merchants
//
//  Created by kingly09 on 2020/7/14.
//  Copyright © 2020 kingly09. All rights reserved.
//

import UIKit
import Alamofire
import Moya
import HandyJSON

let BYNetwork = MyProviderManager()

let MyProvider = MoyaProvider<MultiTarget>(endpointClosure: MoyaProvider.customEndpointMapping, requestClosure: requestClosure, plugins: [BYNetworkActivityPlugin()])

//返回数据转模型(方便判断错误码)
class responseModel: BYBaseModel {
    var data: Any?
    var code: Int = -1 //0为正确码
    var msg: String = ""
    var time: String = ""
    var success: Bool = false

    required init() {}
}

class MyProviderManager: NSObject {

    public func sendRequest(target: MultiTarget,
                            showError: Bool,
                            showNetworkError: Bool = true,
                            success:@escaping (responseModel?)->(),
                            failure:@escaping (MoyaError)->()){
        
        MyProvider.request(target) { result in
            
            switch result{
                case let .success(moyaResponse):

                let data =  moyaResponse.data
                guard !data.isEmpty else{ success(nil); return }
                
//                let statusCode =  moyaResponse.statusCode
//                guard statusCode == 200 else{ success(nil); return }
                
                self.dataHandler(data, target: target, showError: showError, showNetworkError: showNetworkError, success: success, failure: failure)

                case let .failure(error):
                    
                    if showNetworkError {
                        let userInfo = error.errorUserInfo
                        let underlyingError = userInfo["NSUnderlyingError"] as! AFError
                        if underlyingError.isExplicitlyCancelledError != true {
                            Toast(text: "请求失败").show()
                            
                        } else {
                            print("取消请求")
                        }
                    }
                    failure(error)
            }
        }
    }
    
    public func cancelRequest(url:[String]) {
        
        MyProvider.session.session.getTasksWithCompletionHandler { (dataTasks, uploadTasks, downloadTasks) in
                dataTasks.forEach {
                    for item in url {
                        if $0.originalRequest?.url?.absoluteString == item {
                            $0.cancel()
                        }
                    }
                }
        }
        
    }
    
    public func cancelAllRequest() {

        MyProvider.session.cancelAllRequests();

    }
}

extension MyProviderManager{
    
    //json解析(输入字典)
    public func JSONResponseFormatter(_ data: Data) -> NSDictionary? {
        if JSONSerialization.isValidJSONObject(data) {
            return nil
        }
        
        do {
            let dataAsJSON = try JSONSerialization.jsonObject(with: data)
            return dataAsJSON as? NSDictionary
        } catch {
            return nil
        }
    }

    
    func dataHandler(_ data: Data, target:MultiTarget, showError: Bool, showNetworkError: Bool, success:@escaping (responseModel?)->(),
    failure:@escaping (MoyaError)->()){
        
        let dict =  self.JSONResponseFormatter(data)
        print("respose(\(target.path)) ：\(dict ?? [:]) ")
        let model = responseModel.deserialize(from: dict)
        if let model = model{
            if showError {
                if model.code != 0 {
                    Toast(text: model.msg).show()
                }
            }
            success(model)
        }else{
            //如果解析失败返回一个失败状态的responseModel,否则上层强解包崩溃
            let failureModel = responseModel()
            failureModel.success = false
            success(failureModel)
        }

    }
    
    func defaultHeaders() -> [String: String] {
        var params:[String: String] = [:]
        params["channelId"] = ""
        params["deviceId"] = UIDevice.deviceId()
        params["phoneModel"] = UIDevice.modelName()
        params["ipAddress"] = UIDevice.getIpAddress()
        params["sysVersion"] = UIDevice.current.systemVersion
        params["apiVersion"] = Bundle.main.object(forInfoDictionaryKey:"CFBundleShortVersionString") as? String
        params["platform"] = "iOS"
        params["token"] = MBUserInfo.shared.getLoginRspInfo().merToken
//
//        let jsonData = try! JSONSerialization.data(withJSONObject: params, options: [])
//        let str = String(data: jsonData, encoding: .utf8)!
//        let headers = ["headerParam":str,"Authorization":""]
//        print("defaultHeaders-------- \(headers)")
        return params
        
    }

}

extension Response {
    func mapModel<T: HandyJSON>(_ type: T.Type) -> T {
        let jsonString = String.init(data: data, encoding: .utf8)
        print(jsonString as Any)
        return JSONDeserializer<T>.deserializeFrom(json: jsonString)!
    }
}

// MARK: - 设置请求超时时间
let requestClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider<MultiTarget>.RequestResultClosure) in
    
    do {
        var request: URLRequest = try endpoint.urlRequest()
        request.timeoutInterval = 15    //设置请求超时时间
        done(.success(request))
    } catch  {
        print("错误了 \(error)")
    }
    
}
